package com.hrabun.goodmorningalarm;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DigitalClock;

public class WakeUpActivity extends Activity implements OnClickListener {

	MediaPlayer mp;
	Button btnOff;
	DigitalClock clock;
	Ringtone r;
	ExecutorService es;
	Context context;
	Handler hand;
	AudioManager am;
	RadioStation radioStation;
	
	final int HANDLER_MESSAGE_START_DEFAULT = 1;
	final int HANDLER_MESSAGE_STOP = 2;
	final int HANDLER_INCREASE_VOLUME = 3;
	final int HANDLER_PING_STATION_STATUS = 4;
	int radioPlayingTimeout = 1; //in mins
	final int volume_increase_timeout = 2;
	int initialVolume;
	int initialMode;
	int currentVolume = 2;
	boolean isVolumeIncreasing = true;
	int radioConnectionAttempts = 0;
	
	public WakeUpActivity() {
		
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		setContentView(R.layout.wake_up_activity);
		context = MainActivity.getAppContext();
		registerControls();
		readSystemSettings();
		Intent intent = getIntent();
		hand = new Handler(callback);
		String radioId = intent.getExtras().getString("radio");
		radioStation = new RadioStation();
		radioStation = radioStation.getStationById(radioId);
		es = Executors.newFixedThreadPool(1);
		startDefaultHandler();
		wakeUpScreen();
		if (isVolumeIncreasing) {
			rememberInitialVolumeSettings();
			startVolumeIncreasing();
		}
		radioStation.playRadio();
//		es.execute(playRadio(radioStation.getStationURL()));
	}
	
	@SuppressLint("Wakelock")
	private void wakeUpScreen() {
		PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
		WakeLock pmw = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "TAG");
		pmw.acquire();
		this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
	}
	
	private void registerControls () {
		btnOff = (Button) findViewById(R.id.btnOffAlarm);
		btnOff.setTypeface(Global.setFontRibeye());
		clock = (DigitalClock) findViewById(R.id.digitalClock1);
		clock.setTypeface(Global.setFontRibeye());
		clock.setTextSize(52);
		clock.setTextColor(Color.BLACK);
		

		btnOff.setOnClickListener(this);
	}
	
	private void readSystemSettings() {
		isVolumeIncreasing = Global.pref_isVolumeIncreasing();
		radioPlayingTimeout = Global.pref_getRadioTimeoutPreference();
	}
	
	/**
	 * Remember initial volume, then set it to 0
	 */
	private void rememberInitialVolumeSettings() {
		am = (AudioManager) this.getSystemService(AUDIO_SERVICE);
		initialMode = am.getRingerMode();
		initialVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
		am.setStreamVolume(AudioManager.STREAM_MUSIC, 2, 0);
		
	}

	private void restoreVolumeSettings() {
		am.setStreamVolume(AudioManager.STREAM_MUSIC, initialVolume, 0);
		am.setMode(initialMode);
	}
	
	private void removeAllHandlers() {
		hand.removeMessages(HANDLER_MESSAGE_START_DEFAULT);
		hand.removeMessages(HANDLER_MESSAGE_STOP);
		hand.removeMessages(HANDLER_INCREASE_VOLUME);
		hand.removeMessages(HANDLER_PING_STATION_STATUS);
	}
	
	/**
	 * Starting sleep handler to play default ringtone after timeout
	 */
	private void startDefaultHandler() {
		hand.sendEmptyMessageDelayed(HANDLER_MESSAGE_START_DEFAULT, radioPlayingTimeout * 60 * 1000);
		hand.sendEmptyMessageDelayed(HANDLER_PING_STATION_STATUS, 1 * 1000);
	}
	
	/**
	 * Start increasing volume using volume_increase_timeout  (default = 2 sec)
	 */
	private void startVolumeIncreasing() {
		hand.sendEmptyMessageDelayed(HANDLER_INCREASE_VOLUME, volume_increase_timeout * 1000);
	}
	
	@Override
	protected void onPause() {
		radioStop();
		defaultRingtoneStop();
		removeAllHandlers();
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		radioStop();
		defaultRingtoneStop();
		removeAllHandlers();
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnOffAlarm: {
			radioStop();
			defaultRingtoneStop();
			removeAllHandlers();
			closeApp();
		}
			break;

		default:
			break;
		}
		finish();
	}

	Handler.Callback callback = new Handler.Callback() {
		
		@Override
		public boolean handleMessage(Message msg) {
			switch (msg.what) {
			case HANDLER_MESSAGE_START_DEFAULT:
			{
				radioStop();
				defaultRingtoneStart();
				hand.sendEmptyMessageDelayed(HANDLER_MESSAGE_STOP, 60 * 1000);
				hand.removeMessages(HANDLER_PING_STATION_STATUS);
			}	break;
			case HANDLER_MESSAGE_STOP:
			{
				defaultRingtoneStop();
				radioStop();
				removeAllHandlers();
				finish();
			}	break;
			case HANDLER_INCREASE_VOLUME:
			{
				if (am.getStreamVolume(AudioManager.STREAM_MUSIC) != am.getStreamMaxVolume(AudioManager.STREAM_MUSIC)) {
					am.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, 0);
					hand.sendEmptyMessageDelayed(HANDLER_INCREASE_VOLUME, volume_increase_timeout * 1000);
				}
			}	break;
			case HANDLER_PING_STATION_STATUS:
			{
				if (radioStation != null) {
					boolean res = radioStation.isRadioPlaying();
					if (res) {
						btnOff.setEnabled(true);
						btnOff.setText("Dismiss");
						radioConnectionAttempts = 0;
					} else {
						btnOff.setEnabled(false);
						btnOff.setText("Connecting...");
						hand.sendEmptyMessageDelayed(HANDLER_PING_STATION_STATUS, 1 * 1000);
						radioConnectionAttempts++;
					}
				}
				if (radioConnectionAttempts == 10) {
					hand.sendEmptyMessage(HANDLER_MESSAGE_START_DEFAULT);
				}
			}	break;
			default:
				break;
			}
			return false;
		}
	};
	
	private void radioStop() {
		if (radioStation != null)  {
			radioStation.stopRadio();
		}
	}
	
	private void defaultRingtoneStart() {
		if ((r != null ) && (!r.isPlaying())) {
			Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
			if (alert == null) {
				alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
			}
			r = RingtoneManager.getRingtone(getApplicationContext(), alert);
			r.play();
		}
	}
	
	private void defaultRingtoneStop() {
		if ((r != null) && (r.isPlaying())) {
			r.stop();
		}
	}

	private void closeApp() {
		//restore volume and mode
		restoreVolumeSettings();
		finish();
	}
	
//	private void playCustom() {
//	File[] files = new File(Environment.getExternalStorageDirectory()
//			.getPath()).listFiles();
//	mp = new MediaPlayer();
//	try {
//		mp.setDataSource(Environment.getExternalStorageDirectory()
//				.getPath() + "/Maxim - Carmen Queasy.mp3");
//	} catch (IllegalArgumentException e) {
//		// TODO Auto-generated catch block
//		e.printStackTrace();
//	} catch (SecurityException e) {
//		// TODO Auto-generated catch block
//		e.printStackTrace();
//	} catch (IllegalStateException e) {
//		// TODO Auto-generated catch block
//		e.printStackTrace();
//	} catch (IOException e) {
//		// TODO Auto-generated catch block
//		e.printStackTrace();
//	}
//	try {
//		mp.prepare();
//	} catch (IllegalStateException e) {
//		// TODO Auto-generated catch block
//		e.printStackTrace();
//	} catch (IOException e) {
//		// TODO Auto-generated catch block
//		e.printStackTrace();
//	}
//	mp.start();
//}
}
